package library.database;

import com.gooddies.reflection.fieldprocessing.fieldextractors.jdbcExctractor.JdbcFieldFiller;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Dmitry
 */
public class FillerReflectionDatabaseCallback extends AbstractDatabase.DBMultpCallback {
    private JdbcFieldFiller filler;
    private Class typeOfElement;

    public FillerReflectionDatabaseCallback(JdbcFieldFiller filler, Class typeOfElement) {
        this.filler = filler;
        this.typeOfElement = typeOfElement;
        if(filler==null){
            throw new RuntimeException("Filler cannot be null.");
        }
        try{
            typeOfElement.newInstance();
        }catch(Exception ex){
            throw new RuntimeException("Class "+typeOfElement.getCanonicalName()+" does not have default constructor");
        }
    }

    @Override
    public Object getResults(ResultSet rs) throws SQLException {
        try {
            return filler.fill(typeOfElement.newInstance(), rs);
        } catch (InstantiationException | IllegalAccessException ex) {
            throw new RuntimeException("Some error while reading from database. "+ex.toString());
        }
    }
}
